package mspbots.autotask.data.core.companies;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import mspbots.autotask.data.core.AbstractToolsUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * mspbots.core.sync.autotask.badmessage.BadMessageReceiver
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/7/21
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class CompaniesReceiver extends AbstractToolsUtil {

    private final CompaniesRepository companiesRepository;

    @RabbitListener(queues = "auto-task.companies.sync")
    public void syncTask(ResultMsg content) {

        Company company = Company.builder().otherId(content.getId())
                .tenantId(content.getTenantId()).syncTime(content.getSyncDate())
                .createdTime(LocalDateTime.parse(content.getEntity().get("createDate").textValue(),
                        DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .updatedTime(LocalDateTime.parse(content.getEntity().get("lastActivityDate").textValue(),
                        DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .entity(content.getEntity())
                .build();

        if (ObjectUtils.isEmpty(company.getOtherId())) {
            return;
        }

        this.companiesRepository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .map(ticket -> {
                    company.setId(ticket.getId());
                    return company;
                })
                .defaultIfEmpty(company)
                .flatMap(this.companiesRepository::save).block(Duration.ofSeconds(10));
    }

}
